import numpy as np
from PIL import Image

# 将numpy.ndarray图像（通道维度在前）转换为PIL.Image图像
def np2pil(np_image):
    np_image_u8 = np.uint8(np.round(np_image * 255))
    if len(np_image) == 1: # 灰度图
        np_image_u8 = np_image_u8[0] # 去掉通道维度
    else: # RGB
        np_image_u8 = np.transpose(np_image_u8, (1, 2, 0)) # 将通道维度放到最后
    return Image.fromarray(np_image_u8)

# 将PIL.Image图像转换为numpy.ndarray图像（通道维度在前）
def pil2np(pil_image):
    np_image = np.array(pil_image, dtype = np.float32)
    if pil_image.mode == 'L': # 灰度图
        return np.array([np_image]) # 加上通道维度
    else: # RGB
        return np.transpose(np_image, (2, 0, 1)) # 将通道维度放到最前
